﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page
{
	private SqlConnection conn = new SqlConnection();

	protected void Page_Load(object sender, EventArgs e)
	{
		if(!Page.IsPostBack)
		{
			dplDepartment.Items.Add("计算机");
			dplDepartment.Items[dplDepartment.Items.Count-1].Value = "1";//指定新添加的项目的Value值

			dplDepartment.Items.Add("软件工程");
			dplDepartment.Items[dplDepartment.Items.Count - 1].Value = "2";

			dplDepartment.Items.Add("电子工程");
			dplDepartment.Items[dplDepartment.Items.Count - 1].Value = "3";
		}//在下拉菜单中添加3个选项

	}

	protected void btnAdd_Click(object sender, EventArgs e)
	{
		string strConnectionString = "server=127.0.0.1;uid=sa;pwd=;database=School;";//指定数据库连接字符串
		conn.ConnectionString = strConnectionString;//将数据库连接字符串赋值给SqlConnection对象的ConnectionString属性

		string strStudentID = txtID.Text.Trim();//得到用户输入的学号
		string strName = txtName.Text.Trim();
		string strDayOfBirth = txtBirthday.Text.Trim();
		string strGender = "";
		string strDepartmentID = dplDepartment.SelectedValue;//得到用户选择的专业的Value值

		if (rdoMale.Checked)//得到用户选择的性别
		{
			strGender = "男";
		}
		else
		{
			strGender = "女";
		}

		string strCommandText =
			String.Format(
				@"INSERT INTO Student(StudentID, Name, Gender, DayOfBirth, DepartmentID)
									VALUES('{0}', '{1}', '{2}', '{3}', {4});",
				strStudentID, strName, strGender, strDayOfBirth, strDepartmentID);//利用String.Format()函数根据用户输入的参数，生成相应的SQL语句

		try
		{
			conn.Open();//打开数据库连接

			SqlCommand command = new SqlCommand(strCommandText, conn);//创建SqlCommand对象，并指定SQL命令文本与数据库连接对象
			command.ExecuteNonQuery();//执行SQL语句

			Response.Write("学生添加成功");

		}
		catch (Exception exception)
		{

			Response.Write(exception.Message);//若捕捉到异常，输出错误信息
		}
	}
}
